<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 结构 -->
        <div slot="header" class="clearfix">
          <span> 试题录入</span>
        </div>
        <div>
          <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="medium">
            <el-form-item label="学科：" prop="subjectID">
              <el-select placeholder="请选择" v-model="form.subjectID" @change="getDirectoryList()">
                <el-option :label="item.label" :value="item.value" v-for="item in subjectList" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录：" prop="catalogID">
              <el-select placeholder="请选择" v-model="form.catalogID">
                <el-option :label="item.label" :value="item.value" v-for="(item, index) in directoryList" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业：" prop="enterpriseID">
              <el-select placeholder="请选择" v-model="form.enterpriseID">
                <el-option :label="item.company" :value="item.id" v-for="item in enterpriseList" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="city" label="城市：" prop="province">
              <el-select placeholder="请选择" v-model="form.province" @change="getCityList">
                <el-option :label="item" :value="item" v-for="(item, index) in provinceList" :key="index"></el-option>
              </el-select>
              <el-select placeholder="请选择" v-model="form.city">
                <el-option :label="item" :value="item" v-for="(item, index) in cityList" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向：" prop="direction">
              <el-select placeholder="请选择" v-model="form.direction">
                <el-option :label="item" :value="item" v-for="(item, index) in directionList" :key="index"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型：" prop="questionType">
              <el-radio-group @change="questionTypeChange" v-model="form.questionType">
                <el-radio :label="item.value" v-for="(item, index) in questionTypeList" :key="index">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度：" prop="difficulty">
              <el-radio-group v-model="form.difficulty">
                <el-radio :label="item.value" v-for="(item, index) in difficultyList" :key="index">{{ item.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干：" prop="question">
              <quill-editor v-model="form.question" :options="editorOption" @blur="$refs.form.validateField('question')"> </quill-editor>
            </el-form-item>
            <el-form-item label="选项：" v-if="!(form.questionType === 3)">
              <div v-if="form.questionType === '1'">
                <el-row v-for="(item, index) in list" :key="index">
                  <el-col>
                    <el-radio-group v-model="option.code">
                      <el-radio @click.native="change(index, $event)" :true-label="1" :false-label="0" :label="item.isRight"
                        >{{ item.code }}：</el-radio
                      >
                    </el-radio-group>
                    <el-input v-model="data[index].title" style="width: 20%"></el-input>
                    <el-upload action="https://jsonplaceholder.typicode.com/posts/">
                      <span>上传图片</span>
                    </el-upload>
                    <i class="el-icon-circle-close"></i>
                  </el-col>
                </el-row>
              </div>
              <div v-else-if="form.questionType === '2'">
                <el-row v-for="(item, index) in list" :key="index">
                  <el-col>
                    <el-checkbox :true-label="1" :false-label="0" v-model="item.isRight" :label="item.isRight">{{ item.code }}：</el-checkbox>
                    <el-input style="width: 20%" v-model="data[index].title">{{ data }}</el-input>
                    <el-upload action="https://jsonplaceholder.typicode.com/posts/">
                      <span>上传图片</span>
                    </el-upload>
                    <i class="el-icon-circle-close"></i>
                  </el-col>
                </el-row>
              </div>
              <el-row>
                <el-col>
                  <el-button :disabled="form.questionType === '1'" @click="num++" type="danger" icon="el-icon-plus">增加选项与答案</el-button>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="解析视频：">
              <el-input v-model="form.videoURL"></el-input>
            </el-form-item>
            <el-form-item label="答案解析：" prop="question">
              <quill-editor ref="myQuill"  @click.native="handleEditAble" v-model="form.answer" :options="editorOption" @blur="$refs.form.validateField('question')"> </quill-editor>
            </el-form-item>
            <el-form-item label="题目备注:">
              <el-input v-model="form.remarks" type="textarea" :rows="4"></el-input>
            </el-form-item>
            <el-form-item label="试题标签：">
              <el-select v-model="form.tags" multiple placeholder="请选择">
                <el-option v-for="item in tagLIst" :key="item.value" :label="item.label" :value="item.label"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button v-if="$route.query.id" @click="submit" type="success">确认修改</el-button>
              <el-button v-else @click="submit" type="primary">确认提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入
import { simple as getSubjectList } from '@/api/hmmm/subjects'
import { simple as getDirectoryList } from '@/api/hmmm/directorys'
import { list as getEnterpriseList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'
import { simple as getTagList } from '@/api/hmmm/tags'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['blockquote'], // 引用  代码块
  // ['link', 'image', 'video'] // 链接、图片
  ['code-block', 'link', 'image'] // 链接、图片
]
export default {
  data () {
    return {
      data: [],
      num: 4,
      code: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions // 工具栏
          }
        }
      },
      subjectList: [],
      directoryList: [],
      enterpriseList: [],
      provinceList: [],
      cityList: [],
      difficultyList: [],
      questionTypeList: [],
      directionList: direction,
      tagLIst: [],
      option: {
        code: 1,
        items: []
      },
      form: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '',
        city: '',
        direction: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        options: [],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: []
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [
          { required: true, message: '请选择地区', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.form.city === '') {
                callback(new Error('请选择地区'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [
          {
            validator: (rule, value, callback) => {
              if (this.form.question === '') {
                callback(new Error('请输入题干'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    list () {
      // eslint-disable-next-line vue/no-side-effects-in-computed-properties
      return this.$route.query.id ? this.form.options : this.option.items.slice(0, this.num)
    }
  },
  created () {
    this.$nextTick(() => {
      window.scrollTo(0, 0)
    })
    this.getSubjectList()
    this.getEnterpriseList()
    this.getProvincesList()
    this.mapList()
    this.mapData()
    this.getQuestionsDetail()
    this.getTagList()
  },
  mounted () {
    this.$refs.myQuill.quill.enable(false)
  },
  methods: {
    handleEditAble () {
      // console.log(12, this.qillInit)
      // if (this.qillInit) {
      this.$refs.myQuill.quill.enable(true)
      this.$refs.myQuill.quill.focus()
      this.qillInit = false
      // }
    },
    async getTagList () {
      const res = await getTagList({ subjectID: this.data.subjectID })
      console.log(res)
      this.tagLIst = res.data
    },
    async getQuestionsDetail () {
      if (this.$route.query.id) {
        const res = await detail({ id: this.$route.query.id })
        console.log(res, 7878)
        this.form = res.data
        this.option.items = this.form.options
        // this.option.items = res.data.options
        // [{ isRight }]
        // this.option.code = isRight
        if (res.data.tags) this.form.tags = res.data.tags.split(',')
        this.data = res.data.options
        this.getDirectoryList()
      } else {
        this.data = this.option.items.slice(0, this.num)
      }
    },
    async mapData () {
      this.difficultyList = difficulty.map((item) => {
        return {
          value: String(item.value),
          label: item.label
        }
      })
      this.questionTypeList = questionType.map((item) => {
        return {
          value: String(item.value),
          label: item.label
        }
      })
    },
    async getSubjectList () {
      const res = await getSubjectList()
      this.subjectList = res.data
    },
    async getDirectoryList () {
      const res = await getDirectoryList({ subjectID: this.form.subjectID })
      console.log(res, 485)
      this.directoryList = res.data
      if (!this.$route.query.id) {
        this.form.catalogID = ''
        this.form.tags = ''
      }
    },
    async getEnterpriseList () {
      const res = await getEnterpriseList()
      this.enterpriseList = res.data.items
    },
    async getProvincesList () {
      const res = await provinces()
      this.provinceList = res
    },
    async getCityList () {
      this.form.city = ''
      const res = await citys(this.form.province)
      this.cityList = res
    },
    mapList () {
      this.code.forEach((item) => {
        this.option.items.push({
          letter: '',
          code: item,
          title: '',
          img: '',
          isRight: 0
        })
      })
    },
    change (value, item) {
      if (item.target.nodeName === 'SPAN') {
        this.option = {
          code: '',
          items: []
        }
        console.log(value)
        this.form.options = this.data
        this.form.options.forEach((item) => {
          item.isRight = 0
        })
        // this.form.options[value].isRight = 0
        this.form.options[value].isRight = 1
        this.mapList()
        // this.getQuestionsDetail()
        this.option.items[value].isRight = !this.option.items[value].isRight
      }
    },
    questionTypeChange (value) {
      this.data.forEach((item) => {
        item.isRight = 0
      })
      this.option.items.forEach((item) => {
        item.isRight = 0
      })
    },
    submit () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        this.form.options = this.data
        if (this.$route.query.id) {
          this.form.tags = this.form.tags.join(',')
          await update({ id: this.$route.query.id, ...this.form })
          this.$message.success('修改成功')
        } else {
          this.form.options.reverse()
          this.form.tags = this.form.tags.join(',')
          await add(this.form)
          this.$message.success('新增成功')
        }
        this.$router.push('/questions/list')
      })
    }
  }
}
</script>

// 样式
<style lang="scss" scoped>
.city {
  .el-form-item__content {
    display: flex;
    .el-select {
      width: 17%;
      margin-right: 1%;
    }
  }
}
.el-select,
.el-input,
.el-textarea {
  width: 400px;
}

.el-col {
  display: flex;
  align-items: center;
  i {
    position: relative;
    top: -30px;
    right: 12px;
    font-size: 20px;
    color: #999;
    background-color: #fff;
  }
  .el-radio {
    margin-right: 0;
  }
}

.quill-editor {
  ::v-deep .ql-container {
    height: 240px;
  }
}

::v-deep .el-upload {
  position: relative;
  top: 6px;
  margin-left: 5px;
  width: 100px;
  height: 60px;
  border: 1px dashed #999;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  span {
    line-height: 60px;
  }
  &:hover {
    border-color: #409eff;
  }
}
</style>
